from typing import Any, Optional

from pydantic import BaseModel, Field


class SSEMessage(BaseModel):
    """SSE消息模型"""

    event: str = Field(..., description="事件类型")
    data: dict[str, Any] = Field(..., description="消息数据")
    id: Optional[str] = Field(default=None, description="消息ID")

    def to_sse_format(self) -> str:
        """转换为SSE格式"""
        lines = []
        if self.id:
            lines.append(f"id: {self.id}")
        lines.append(f"event: {self.event}")
        lines.append(f"data: {self.model_dump_json()}")
        lines.append("")
        return "\n".join(lines) + "\n"
